<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/10/10 17:07
 */

namespace module\ai\library\channel\llm;

use module\ai\library\channel\abstract\Llm;
use module\ai\library\channel\completion\DoubaoCompletion;
use module\ai\library\channel\interface\CompletionInterface;
use Psr\Http\Message\ResponseInterface;

class Doubao extends Llm
{
    protected string $baseUrl = 'https://ark.cn-beijing.volces.com/api/v3/chat/completions';
    /**
     * @inheritDoc
     */
    protected function getCompletionStruct(array $data, bool $isStream = false): ?CompletionInterface
    {
        return new DoubaoCompletion($data, $isStream);
    }

    /**
     * @inheritDoc
     */
    public static function versions(): array
    {
        // TODO: Implement versions() method.
    }

    /**
     * @inheritdoc
     */
    protected function setPayload(array $config, bool $override = false): void
    {
        parent::setPayload($config, $override);

        $keys = [
            'max_tokens', 'top_p', 'temperature', 'stop',
            'repetition_penalty', 'presence_penalty',
        ];
        foreach ($keys as $key) {
            if (isset($config[$key]) && strlen($config[$key]) > 0) {
                $this->payload[$key] = is_numeric($config[$key]) ? floatval($config[$key]) : $config[$key];
            }
        }
    }

    protected function getPayload(): array
    {
        $result = parent::getPayload();
        if (!empty($result['stream'])) {
            $result['stream_options'] = [
                'include_usage' => true
            ];
        }
        return $result;
    }

    protected function getResponse(bool $isStream = false, array $clientOptions = []): ResponseInterface
    {
        return parent::getResponse($isStream, [
            'headers' => [
                'Content-Type'  => 'application/json',
                'Authorization' => vsprintf("Bearer %s", [
                    $this->getKeyModel()?->config['api_key'],
                ]),
            ]
        ]);
    }
}